const BASE_URL = 'https://api.huhuiyu.top'
const TOKEN_KEY = BASE_URL + '_token'

const tokeninfo = {
  save: (data) => {
    if (data && data.token) {
      uni.setStorageSync(TOKEN_KEY, data.token)
    }
  },
  load: () => {
    const token = uni.getStorageSync(TOKEN_KEY)
    return token ? token : ''
  },
  remove: () => {
    uni.removeStorageSync(TOKEN_KEY)
  }

}

const api = {
  send: (url, param, cb, method) => {
    uni.request({
      url: BASE_URL + url,
      method: method,
      data: param,
      header: {
        Authorization: tokeninfo.load()
      },
      success: (resp) => {
        tokeninfo.save(resp.data)
        cb(resp.data)
      },
      fail: (error) => {
        console.log(error)
        cb({
          success: false,
          message: 'bug了',
          code: 500
        })
      }
    })
  },
  get: (url, param, cb) => {
    api.send(url, param, cb, 'GET')
  },
  post: (url, param, cb) => {
    api.send(url, param, cb, 'POST')
  },
  put: (url, param, cb) => {
    api.send(url, param, cb, 'PUT')
  },
  delete: (url, param, cb) => {
    api.send(url, param, cb, 'DELETE')
  },
  patch: (url, param, cb) => {
    api.send(url, param, cb, 'PATCH')
  }
}

const tools = {
  userlogo: (uid) => {
    return `${BASE_URL}/user/logo/${uid}`
  },
  concatJson: (...jsons) => {
    let json = {};
    for (let index = 0; index < jsons.length; index++) {
      let element = jsons[index];
      for (let key in element) {
        json[key] = element[key];
      }
    }
    return json;
  },
  formatDate: (value, format = 'yyyy-MM-dd hh:mm:ss') => {
    try {
      let time = new Date();
      if (typeof value === 'number') {
        time.setTime(parseInt(value.toString()));
      } else if (value instanceof Date) {
        time = value;
      }
      let year = time.getFullYear() + '';
      let month = time.getMonth() + 1 + '';
      let day = time.getDate() + '';
      let hour = time.getHours() + '';
      let minute = time.getMinutes() + '';
      let second = time.getSeconds() + '';
      let ms = time.getMilliseconds() + '';
      month = month.padStart(2, '0');
      day = day.padStart(2, '0');
      hour = hour.padStart(2, '0');
      minute = minute.padStart(2, '0');
      second = second.padStart(2, '0');
      ms = ms.padStart(3, '0');

      format = format.replace(/yyyy/g, year);
      format = format.replace(/MM/g, month);
      format = format.replace(/dd/g, day);
      format = format.replace(/hh/g, hour);
      format = format.replace(/mm/g, minute);
      format = format.replace(/ss/g, second);
      format = format.replace(/ms/g, ms);
      return format;
    } catch (ex) {
      console.error(ex);
      return '';
    }
  }

}

export {
  api as
  default, api as api, tools as tools
}